/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.thienloc.omap.controller.broadcast;

import com.thienloc.omap.controller.AbstractCrudBean;
import com.thienloc.omap.entity.Broadcast;
import com.thienloc.omap.entity.BroadcastTemp;
import com.thienloc.omap.session.BroadcastFacade;
import com.thienloc.omap.session.BroadcastTempFacade;
import com.thienloc.omap.util.JsfUtil;
import java.util.Date;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.ViewScoped;

/**
 *
 * @author GiangLT
 */
@ManagedBean
@ViewScoped
public class BroadcastBean extends AbstractCrudBean {

    @EJB
    private BroadcastFacade facade;
    @EJB
    private BroadcastTempFacade broadcastTempFacade;
    @ManagedProperty(value = "#{broadcastConfigBean}")
    private BroadcastConfigBean broadcastConfigBean;
    private Broadcast selected;
    private List<Broadcast> list;
    private List<Broadcast> completedList;
    private List<Broadcast> waitingList;
    private List<Broadcast> blackList;
    private List<Broadcast> invalidList;
    private String mdnList;
    protected Broadcast[] selectedList;
    private String remainingTime;
    private String controlButtonImage = "ui-icon ui-icon-play";
    private String controlButtonTitle = "Chạy";

    @Override
    protected void validateForm() throws Exception {
    }

//    @PostConstruct
//    public void updateBroadcastStatus() {
//        try {
//            completedList = facade.findByStatus("COMPLETED");
//            waitingList = facade.findByStatus("WAITING");
//            long remain = Long.valueOf(broadcastConfigBean.getSelected().getSpeed()) * waitingList.size();
//            remainingTime = getElapsedTimeHoursMinutesSecondsString(remain);
//        } catch (Exception ex) {
//            logAndNotifyError(ex);
//        }
//    }
    public String getElapsedTimeHoursMinutesSecondsString(Long timeInSeconds) {
        String format = String.format("%%0%dd", 2);
        String seconds = String.format(format, ((timeInSeconds % 3600) % 60));
        String minutes = String.format(format, (timeInSeconds % 3600) / 60);
        String hours = String.format(format, timeInSeconds / 3600);
        String result = hours + ":" + minutes + ":" + seconds;
        return result;
    }

    public void sendSms() {
        try {
            BroadcastTemp broadcastTemp = new BroadcastTemp();
            broadcastTemp.setContent(selected.getContent());
            broadcastTemp.setMsisdn(selected.getMsisdn());

            broadcastTempFacade.create(broadcastTemp);
        } catch (Exception ex) {
            logAndNotifyError(ex);
        }
    }

    @Override
    protected Logger getLogger() {
        return LoggerFactory.getLogger(BroadcastBean.class);
    }

    @Override
    protected void resetToCreateFormAction() throws Exception {
        list = facade.findAll();
        selected = new Broadcast();
        edit = false;
        view = false;
        this.mdnList = "";
    }

    @Override
    protected void findSelected(int id) throws Exception {
        selected = facade.find(id);
    }

    @Override
    protected void createSelected() throws Exception {
        facade.create(selected);
        resetToCreateForm();
        JsfUtil.addSuccessMessage("Thành công!", "Đã thêm mới thành công một bản ghi");
    }

    @Override
    protected void editSelected() throws Exception {
        facade.edit(selected);
        resetToCreateForm();
        JsfUtil.addSuccessMessage("Thành công!", "Đã cập nhật thành công một bản ghi");
    }

    @Override
    protected void removeSelected() throws Exception {
        int size = selectedList.length;
        if (size == 0) {
            JsfUtil.addMessage(FacesMessage.SEVERITY_WARN, "Không có gì để xóa", "Hãy click chọn các bản ghi cần xóa");
            return;
        }
        for (Broadcast item : selectedList) {
            facade.remove(item);
        }
        resetToCreateForm();
        JsfUtil.addSuccessMessage("Thành công!", "Đã xóa thành công " + size + " bản ghi");
    }

    @Override
    protected void prepareViewAction() throws Exception {
        view = true;
        edit = false;
        if (selectedList == null || selectedList.length == 0) {
            JsfUtil.addErrorMessage("Lỗi", "Bạn chưa tích chọn bản ghi cần hiển thị");
            return;
        }
        selected = selectedList[0];
        if (selectedList.length > 1) {
            JsfUtil.addMessage(FacesMessage.SEVERITY_WARN, "Cảnh báo hiển thị", "Bạn đã chọn nhiều hơn 1 bản ghi. Chỉ bản ghi trên cùng được hiển thị");
        }
    }

    @Override
    protected void prepareEditAction() throws Exception {
        view = false;
        edit = true;
        if (selectedList == null || selectedList.length == 0) {
            JsfUtil.addErrorMessage("Lỗi", "Bạn chưa tích chọn bản ghi cần hiển thị");
            return;
        }
        selected = selectedList[0];
        if (selectedList.length > 1) {
            JsfUtil.addMessage(FacesMessage.SEVERITY_WARN, "Cảnh báo hiển thị", "Bạn đã chọn nhiều hơn 1 bản ghi. Chỉ bản ghi trên cùng được hiển thị");
        }
    }

    public void insertList() {
        try {
            String[] mdns = mdnList.split("\\r\\n");
            for (String mdn : mdns) {
                Broadcast Broadcast = new Broadcast();
                Broadcast.setContent(selected.getContent());
                Broadcast.setLastUpdateTime(new Date());
                Broadcast.setMsisdn(mdn);
                Broadcast.setStatus("WAITING");
                facade.create(Broadcast);
            }
            resetToCreateForm();
            JsfUtil.addSuccessMessage("Thành công!", "Đã thêm mới thành công " + mdns.length + " bản ghi");
        } catch (Exception ex) {
            logAndNotifyError(ex);
        }
    }

    public List<Broadcast> getList() {
        return list;
    }

    public void setList(List<Broadcast> list) {
        this.list = list;
    }

    public Broadcast getSelected() {
        return selected;
    }

    public void setSelected(Broadcast selected) {
        this.selected = selected;
    }

    public String getMdnList() {
        return mdnList;
    }

    public void setMdnList(String mdnList) {
        this.mdnList = mdnList;
    }

    public Broadcast[] getSelectedList() {
        return selectedList;
    }

    public void setSelectedList(Broadcast[] selectedList) {
        this.selectedList = selectedList;
    }

    public String getRemainingTime() {
        return remainingTime;
    }

    public void setRemainingTime(String remainingTime) {
        this.remainingTime = remainingTime;
    }

    public BroadcastConfigBean getBroadcastConfigBean() {
        return broadcastConfigBean;
    }

    public void setBroadcastConfigBean(BroadcastConfigBean broadcastConfigBean) {
        this.broadcastConfigBean = broadcastConfigBean;
    }

    public List<Broadcast> getCompletedList() {
        return completedList;
    }

    public List<Broadcast> getWaitingList() {
        return waitingList;
    }

    public List<Broadcast> getBlackList() {
        return blackList;
    }

    public List<Broadcast> getInvalidList() {
        return invalidList;
    }

    public String getCompletedListString() {
        StringBuilder sb = new StringBuilder();
        for (Broadcast broadcast : completedList) {
            sb.append(broadcast.getMsisdn());
            sb.append("\n");
        }
        return sb.toString();
    }

    public String getWaitingListString() {
        StringBuilder sb = new StringBuilder();
        for (Broadcast broadcast : waitingList) {
            sb.append(broadcast.getMsisdn());
            sb.append("\n");
        }
        return sb.toString();
    }

    public String getControlButtonImage() {
        return controlButtonImage;
    }

    public String getControlButtonTitle() {
        return controlButtonTitle;
    }
}
